﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using OpenNETCF.Barcode.Decoders;

namespace OpenNETCF.Barcode
{
    public partial class decode : Form
    {
        Recognizer Processor;

        public decode()
        {
            InitializeComponent();
            barcodePicture.YPos = 50;
            Processor = new Recognizer();
        }

        private void load_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();
            ofd.InitialDirectory = Application.StartupPath;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                imagePath.Text = ofd.FileName;

                var bmp = new Bitmap(imagePath.Text);

                barcodePicture.Image = bmp;
                Processor.LoadImage(bmp, Symbology.UPCvA);

                UpdateLuminanceGraph();

                luminanceChart1.Refresh();
            }

        }

        private void UpdateLuminanceGraph()
        {
            var data = Processor.GetLuminanceLine(barcodePicture.Image.Height * barcodePicture.YPos / 100, 0);
            luminanceChart1.Data = data;
            UpdateBinaryGraph();
        }

        private void UpdateBinaryGraph()
        {
            luminanceChart2.Data = Processor.GetBinaryLuminanceLine(barcodePicture.Image.Height * barcodePicture.YPos / 100, 0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                decoded.Text = Processor.Decode().Value;
            }
            catch
            {
                decoded.Text = "Failed";
            }
        }

        private void threshold_ValueChanged(object sender, EventArgs e)
        {
            var value = (byte)(255 - threshold.Value);
            threshVal.Text = value.ToString();
            Processor.LuminanceThreshold = value;
            UpdateBinaryGraph();
        }

        private void scanY_ValueChanged(object sender, EventArgs e)
        {
            barcodePicture.YPos = 100 - scanY.Value;
            UpdateLuminanceGraph();
        }

        private void bounds_Click(object sender, EventArgs e)
        {
            var r = Processor.GetBarcodeBounds();
            barcodePicture.BarcodeBounds = r;
        }
    }
}
